package cn.itcast.bos.web.action.base;


import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Controller
@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

    @Autowired
    private AreaService areaService;

    //上传文件
    private File file;
    //接受上传的文件名
    private String fileFileName;

    public void setFile(File file) {
        this.file = file;
    }

    /**
     *
     * @param fileFileName
     */
    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    /**
     *
     * @return
     * @throws IOException
     */
    @Action(value = "area_batchImport")
    public String batchImport () throws IOException {
        String msg = null;
        try {
            //System.out.println(file);
            //增强上传功能,添加对xlsx表格文件的支持
            Workbook workbook = null;
            List<Area> areas = new ArrayList<>();
            //将文件传入到进来,判断文件类型.
            if (fileFileName.endsWith(".xls")) {
                workbook = new HSSFWorkbook(new  FileInputStream(file));
            }else{
                //接受.xlsx的文件
                workbook = new XSSFWorkbook(file);
            }
            //读取第一个sheet
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                //遍历每一行                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    ,iter快捷键foreach,跳过第一行
                if (row.getRowNum() ==0) {
                    continue;
                }
                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
                    continue;
                }
                Area area = new Area();
                area.setId(row.getCell(0).getStringCellValue());
                area.setProvince(row.getCell(1).getStringCellValue());
                area.setCity(row.getCell(2).getStringCellValue());
                area.setDistrict(row.getCell(3).getStringCellValue());
                area.setPostcode(row.getCell(4).getStringCellValue());
                //基于pinyin4j生成城市简码
                String province = area.getProvince();
                String city = area.getCity();
                String district = area.getDistrict();
                //截取省市区字符串
                province = province.substring(0, province.length() - 1);
                //截取省,河南--省,郑州--市,中牟--县
                city = city.substring(0,city.length()-1);
                district = district.substring(0,district.length()-1);
                //简码
                String[] headByString = PinYin4jUtils.getHeadByString(province + city + district);
                StringBuffer stringBuffer = new StringBuffer();
                //将数组中的每一个字符拼接到一起
                for (String headStr : headByString) {
                    stringBuffer.append(headStr);
                }
                area.setShortcode(stringBuffer.toString());
                //城市编码
                String citycode = PinYin4jUtils.hanziToPinyin(city, "");
                area.setCitycode(citycode);

                areas.add(area);

            }
            areaService.saveBatch(areas);
            msg = "上传成功...";
        } catch (Exception e) {
            e.printStackTrace();
            msg = "上传失败...";
        }
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().write(msg);

        return NONE;
    }

    //分页多条件查询


    @Action(value = "area_pageQuery",results = {@Result(name = "success",type = "json"),
            @Result(name = "input",location = "/index.html")})
    public String pageQuery(){
        Pageable pageable = new PageRequest(page-1,rows);
        Specification<Area> specification = new Specification<Area>() {
            @Override
            public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //添加查询条件,
                //创建一个list集合将数据封装到一起
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(model.getProvince())) {
                    //创建条件语句
                    Predicate p1 = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
                    list.add(p1);
                }
                if (StringUtils.isNotBlank(model.getCity())) {
                    Predicate p2 = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");
                    list.add(p2);
                }
                if (StringUtils.isNotBlank(model.getDistrict())) {
                    Predicate p3 = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
                    list.add(p3);
                }
                //拼装条件
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Page<Area> pageData = areaService.pageQuery(specification,pageable);

        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }

    /**
     * 区域文件下载到excel中
     * @return
     */
    @Action(value = "area_export")
    public String export(){
        try {
            //将区域文件导出成excel文件
            //1.先将所有的区域文件查找出来
            List<Area> areas = areaService.findAll();
            //对可能超出的数据进行分页输出
            //System.out.println(areas.get(1));
            //2.将集合数据写入到excel中
            //2.1创建一个XSSFWorkbook文件
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook();

            int totalNum = (int) Math.ceil(areas.size() * 1.0 / 1000);
            for (int i = 0; i < totalNum; i++) {
                //2.2创建一个sheet 可以命名工作簿的名字
                XSSFSheet sheet = xssfWorkbook.createSheet("区域数据表"+(i+1));
                //2.3创建一个row表头行第一行
                XSSFRow firstRow = sheet.createRow(0);
                //设置表头的名字
                firstRow.createCell(0).setCellValue("区域编号");
                firstRow.createCell(1).setCellValue("省/自治区/直辖市");
                firstRow.createCell(2).setCellValue("市");
                firstRow.createCell(3).setCellValue("城市编码");
                firstRow.createCell(4).setCellValue("区");
                firstRow.createCell(5).setCellValue("简码");

                int start = i*1000;
                int end = (i+1)*1000;
                if (end>=areas.size()) {
                    end = areas.size();
                }
                for (int j = start; j < end; j++) {
                    XSSFRow row = sheet.createRow(sheet.getLastRowNum()+1);
                    //获取最后一行的行号
                    Area area = areas.get(j);
                    row.createCell(0).setCellValue(area.getId());
                    row.createCell(1).setCellValue(area.getProvince());
                    row.createCell(2).setCellValue(area.getCity());
                    row.createCell(3).setCellValue(area.getCitycode());
                    row.createCell(4).setCellValue(area.getDistrict());
                    row.createCell(5).setCellValue(area.getShortcode());

                }
            }
            //获取输出流
            HttpServletResponse response = ServletActionContext.getResponse();
            //文件下载两个头一个流
            String fileName = "qysjb.xlsx";
            String mimeType = ServletActionContext.getServletContext().getMimeType(fileName);
            response.setContentType(mimeType);
            //fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
            //System.out.println(fileName);
            response.setHeader("content-disposition","attachment;filename="+fileName);
            //2.4写入数据
            xssfWorkbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return NONE;
    }

    @Action(value = "area_findAll",results = {@Result(name = "success",type = "json"),
                @Result(name = "input",location = "/index.html",type = "redirect")})
    public String areaFindAll(){
        List<Area> areas = areaService.findAll();
        ActionContext.getContext().getValueStack().push(areas);
        //System.out.println(areas);
        return SUCCESS;
    }
}
